package com.xigua.JucOfBeautiful.chapterSix._6_1;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/2/223:07
 */
public class FIFOMutex {

    private final AtomicBoolean locked = new AtomicBoolean();

    private final Queue<Thread> waites = new ConcurrentLinkedDeque<Thread>();

    public void lock(){
        boolean wasInterrupted = false;
        Thread current = Thread.currentThread();
        waites.add(current);

        while (waites.peek() != current || !locked.compareAndSet(false,true)){
            LockSupport.park(this);
            if (Thread.interrupted()) wasInterrupted = true;
        }

        waites.remove();
        if (wasInterrupted) current.interrupt();
    }

    public void unlock(){
        locked.set(false);
        LockSupport.unpark(waites.peek());
    }

    public static void main(String[] args) {
        System.out.println();
    }

}
